//
//  LocalNotification.swift
//  FearfulNotification
//
//  Created by 筱鹏 on 2017/9/28.
//  Copyright © 2017年 筱鹏. All rights reserved.
//

import UIKit
import UserNotifications

let FNLNIdentifierKey: String = "FNLNIdentifier"

class LocalNotification: NSObject {

    static let shared: LocalNotification = LocalNotification()
    
    class func configIdentifier() -> String {
        let count = Date().timeIntervalSince1970
        let string = "localNotificationIdentifier_\(count)"
        return string
    }
    
    /**添加指定日并以月为循环单位的通知*/
    class func addMonth(repeats:Bool, _ date: Date, _ title: String?, _ body: String?, _ subtitle: String?, _ identifier: String) {
        self.add(date: date, title, body, subtitle, identifier, repeats, [.day, .hour, .minute])
    }
    
    /**添加指定星期并以星期为循环单位的通知*/
    class func addWeekday(repeats:Bool, _ date: Date, _ title: String?, _ body: String?, _ subtitle: String?, _ identifier: String) {
        self.add(date: date, title, body, subtitle, identifier, repeats, [.weekday, .hour, .minute])
    }
    
    /**添加以天为循环单位的通知*/
    class func addDay(repeats:Bool, _ date: Date, _ title: String?, _ body: String?, _ subtitle: String?, _ identifier: String) {
        self.add(date: date, title, body, subtitle, identifier, repeats, [.hour, .minute])
    }
    
    /**添加指定日期的通知*/
    class func addOneDay(_ date: Date, _ title: String?, _ body: String?, _ subtitle: String?, _ identifier: String, _ completionHandler: ((Error?) -> Swift.Void)? = nil) {
        self.add(date: date, title, body, subtitle, identifier, false, [.era, .year, .month, .day, .hour, .minute], completionHandler)
    }
    
    private class func add(date: Date, _ title: String?, _ body: String?, _ subtitle: String?, _ identifier: String, _ repeats:Bool, _ comset:Set<Calendar.Component>, _ completionHandler: ((Error?) -> Swift.Void)? = nil) {
        if #available(iOS 10.0, *) {
            let center = UNUserNotificationCenter.current()
            let content = UNMutableNotificationContent()
            if let tit = title {
                content.title = tit
            }
            if let bod = body {
                content.body = bod
            }
            if let subtit = subtitle {
                content.subtitle = subtit
            }
            content.sound = UNNotificationSound(named: convertToUNNotificationSoundName("notificationMusic.m4a"))
            
            let calendar = Calendar.current
            let dateCom = calendar.dateComponents(comset, from: date)
            
            let trier = UNCalendarNotificationTrigger(dateMatching: dateCom, repeats: repeats)
            let request = UNNotificationRequest(identifier: identifier, content: content, trigger: trier)
            center.add(request, withCompletionHandler: completionHandler)
        } else {
            let noti = UILocalNotification()
            if let bod = body {
                noti.alertBody = bod
            }
            if let tit = title {
                noti.alertTitle = tit
            }
            noti.soundName = "notificationMusic.m4a"
            noti.userInfo = [FNLNIdentifierKey:identifier]
            noti.fireDate = date;
            if repeats {
                if comset.contains(.weekday) {
                    noti.repeatInterval = .weekday
                } else if comset.contains(.day) {
                    noti.repeatInterval = .month
                } else if comset.contains(.hour) {
                    noti.repeatInterval = .day
                }
            }
            
            UIApplication.shared.scheduleLocalNotification(noti)
        }
    }
    
    class func remove(identifier: String) {
        if #available(iOS 10.0, *) {
            let center = UNUserNotificationCenter.current()
            center.removePendingNotificationRequests(withIdentifiers: [identifier])
        } else {
            if let notifications = UIApplication.shared.scheduledLocalNotifications {
                for localNoti in notifications {
                    guard let userInfo = localNoti.userInfo else {return}
                    guard let iden = userInfo[FNLNIdentifierKey] as? String else {return}
                    if iden == identifier {
                        UIApplication.shared.cancelLocalNotification(localNoti)
                    }
                }
            }
        }
    }
    
    @available(iOS 10.0, *)
    class func getPendingNotificationRequest(completionHandler: @escaping ([UNNotificationRequest]) -> Swift.Void) {
        let center = UNUserNotificationCenter.current()
        center.getPendingNotificationRequests { (requests) in
            DispatchQueue.main.async {
                completionHandler(requests)
            }
        }
    }
    
    class func getLocalNotification(completionHandler: @escaping ([UILocalNotification]) -> Swift.Void) {
        if let notifications = UIApplication.shared.scheduledLocalNotifications {
            completionHandler(notifications)
        }
    }
    
}


extension LocalNotification: UNUserNotificationCenterDelegate {
    
    @available(iOS 10.0, *)
    func userNotificationCenter(_ center: UNUserNotificationCenter, didReceive response: UNNotificationResponse, withCompletionHandler completionHandler: @escaping () -> Void) {
        Event.message("didReceive \(center) response \(response)")
        completionHandler()
    }
    
    @available(iOS 10.0, *)
    func userNotificationCenter(_ center: UNUserNotificationCenter, willPresent notification: UNNotification, withCompletionHandler completionHandler: @escaping (UNNotificationPresentationOptions) -> Void) {
        Event.message("willPresent \(center) response \(notification)")
        completionHandler([.alert,.badge,.sound])
    }
}

// Helper function inserted by Swift 4.2 migrator.
fileprivate func convertToUNNotificationSoundName(_ input: String) -> UNNotificationSoundName {
	return UNNotificationSoundName(rawValue: input)
}
